package com.meida.paotui.app.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.meida.app.provider.handler.LoginHandler;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.utils.FlymeUtils;
import com.meida.module.user.client.dto.LoginParams;
import com.meida.module.user.client.entity.AppAccount;
import com.meida.module.user.client.entity.AppUser;
import com.meida.module.user.provider.service.AppAccountService;
import com.meida.module.user.provider.service.AppUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component(value = "userLoginHandler")
public class UserLoginHandler implements LoginHandler {
    @Autowired
    private AppUserService userService;
    @Autowired
    private AppAccountService accountService;


    /**
     * 登陆前验证拦截
     * @param loginParams
     * @return
     */
    @Override
    public ResultBody beforLogin(LoginParams loginParams) {
        AppUser appUser = userService.getUserByMobile(loginParams.getUsername());
           if(FlymeUtils.isNotEmpty(appUser)){
               if(!appUser.getUserType().equals(loginParams.getUserType())){
                   return  ResultBody.failed("账户类型不匹配");
               }
           }
        return ResultBody.ok();
    }

    /**
     * 登陆后信息扩展
     * @param map
     * @param loginParams
     * @return
     */
    @Override
    public ResultBody afterLogin(Map<String, Object> map, LoginParams loginParams) {
        AppUser appUser=null;
        if(loginParams.getUsername().length()>11){
            QueryWrapper<AppAccount> qw=new QueryWrapper();
            qw.eq("account",loginParams.getUsername());
            AppAccount account=accountService.getOne(qw);
            appUser =userService.getById(account.getUserId());
        }else{
           appUser = userService.getUserByMobile(loginParams.getUsername());
        }
        map.put("User", appUser);

       return ResultBody.ok();
    }
}
